package com.atguigu.state;

import com.atguigu.bean.WaterSensor;
import com.atguigu.utils.MyUtils;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * Created by RUI on 2021/6/15 16:48
 *
 * 针对每个传感器输出最高的3个水位值
 */
public class State_Key_list {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(3);

        env.socketTextStream("hadoop162",9999)
                .map(value -> {
                    String[] split = value.split(",");
                    return new WaterSensor(split[0],Long.valueOf(split[1]),Integer.valueOf(split[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private ListState<Integer> listState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        listState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("listState", Integer.class));

                    }

                    @Override
                    public void processElement(WaterSensor ws,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        listState.add(ws.getVc());
                        Iterable<Integer> it = listState.get();

                        List<Integer> toList = MyUtils.toList(it);
                        toList.sort((o1, o2) -> o2 - o1);

                        if (toList.size() > 3)
                            toList.remove(toList.size()-1);

                        listState.update(toList);

                        out.collect(toList.toString());
                    }
                })
                .print();

        env.execute();
    }
}
